package cn.fotoit.product.app1.service;
import cn.fotoit.product.app1.entity.Menu;
import cn.fotoit.product.app1.repository.MenuRepository;
import cn.fotoit.product.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;


@Service
@CacheConfig(cacheNames = "queue_management_menuService")
@Transactional(readOnly = true)
public class MenuService {
    @Autowired
    private MenuRepository menuRepository;

    @CacheEvict(allEntries = true)
    @Transactional
    public void add(Menu menu) {
        menuRepository.save(menu);
    }

    @CacheEvict(allEntries = true)
    @Transactional
    public void deleteById(Integer id) {
        menuRepository.deleteById(id);
    }

    @CacheEvict(allEntries = true)
    @Transactional
    public void updateNotNull(Menu menu) {
        Optional<Menu> byId = menuRepository.findById(menu.getId());
        if (byId.isPresent()) {
            Menu obj = byId.get();
            BeanUtil.copyPropertiesIgnoreNull(menu, obj);
            menuRepository.save(obj);
        }
    }

    @Cacheable(key = "'findAll'+#page+'size'+#size")
    public Page<Menu> findAll(Integer page, Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        return menuRepository.findAll(pageable);
    }

    @Cacheable(key = "'findById'+#id")
    public Menu findById(Integer id) {
        Optional<Menu> byId = menuRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

}